<?php
    /**
    * @subpackage Controllers
    * @package Modules
    * @author Daniel Huynh
    * @copyright Daniel Huynh
    */

    class urlclickController extends expController {
        public $useractions = array(
        'showall'=>'Show all'
        );
        //public $add_permissions = array('show'=>'View Links');
        //public $remove_permissions = array('edit');
        public $remove_configs = array(
        'comments',
        'ealerts',
        'facebook',
        'files',
        'pagination',
        'rss',
        'tags',
        'twitter',
        );  // all options: ('aggregation','categories','comments','ealerts','facebook','files','pagination','rss','tags','twitter',)

        static function requiresConfiguration() { return true; }
        static function displayname() { return gt("URL Click"); }
        static function description() { return gt("Function click URLs"); }
        static function author() { return "Daniel Huynh "; }
        static function isSearchable() { return false; }

        function showall() {
            expHistory::set('viewable', $this->params);
            $modelname = $this->basemodel_name;
            $where = $this->hasSources() ? $this->aggregateWhereClause() : null;
            $limit = isset($this->config['limit']) ? $this->config['limit'] : null;
            $order = isset($this->config['order']) ? $this->config['order'] : "rank";
            $links = $this->$modelname->find('all', $where, $order, $limit);

            if (empty($this->config['usecategories']) ? false : $this->config['usecategories']) {
                expCatController::addCats($links,$order,!empty($this->config['uncat'])?$this->config['uncat']:gt('Not Categorized'));
                $cats[] = new stdClass();
                $cats[0]->name = '';
                expCatController::sortedByCats($links,$cats);
                assign_to_template(array(
                'cats'=>$cats
                ));
            }
            assign_to_template(array(
            'items'=>$links,
            //            'rank'=>($order==='rank')?1:0
            ));
        }

        public function show() {
            redirect_to(array("controller"=>'links',"action"=>'showall',"src"=>$this->loc->src));
        }
        public function getall()
        {

            assign_to_template(array(
            'cats'=>'test',
            'error'=>0
            ));
            $data= json_encode(array(
            'pa'=>'http://exp/index.php?controller=urlclick&action=getall',
            'ga'=>'ấccscccscs'
            ));
            $x=time();
            $a= expCore::sencode($data,$x);
            $b=expCore::sdecode($a,$x);

            echo "$a <br> $b<br>";

        }
        //Thuật toán:
        /*
        *   link: abc.com/go/{$encode}
        * Key: md5(time)
        * Lưu vào session: ((time * 5)+7)*3
        * Lấy từ session: time= ((ss/3)-7)/5
        *  $encode=array('id'=>$id
        * 'salt'=>{lưu trong database(char8)}crc32b($url)
        * );
        *                  
        */

        public function go()  
        {
            global $db,$user;   
            if(!$user->isLoggedIn())
            {

                assign_to_template(array( 
                'error'=> 3
                ));
                return false;
            }           
            $code = $this->params['code'];
            $key= md5((int)expSession::get("stime"));
            $data_de= json_decode(expCore::sdecode($code,$key));
            //Set begin timer  
            $_SESSION["capt_time"]=time();
            $data=$db->selectObject('urlclick_list',"id={$data_de->id}");
            //Check session 
            if(expSession::get('s_url')!=null&&expSession::get('s_url')!=$data->link)
            {
                echo "Không mở nhiều cửa sổ cùng lúc!";
                assign_to_template(array( 
                'error'=> 1
                ));
                return false;
            }  
            //Check log
            //time() + 24*60*60;
            $_last_day= time() - 24*60*60; 
            $logs=$db->selectObject('urlclick_user_logs',"link_id={$data_de->id} AND user_id={$user->id} AND time<$_last_day"); 
            if($logs!=null)
            {
                assign_to_template(array( 
                'error'=> 2
                ));
                return false; 

            };
            if($data_de->salt==$data->salt&&$data_de->uid==$user->id)
            {
                expSession::set('s_url',$data->id);
                $data->timeout=$data->timeout==0?10:$data->timeout;
                assign_to_template(array(
                'data'=>$data,
                'code'=> $code
                ));

            }
            else
            {
                expQueue::flashAndFlow('error', gt('The requested action could not be performed: Action not found'));
                 assign_to_template(array( 
                'error'=> 4
                ));
                return false;
            }

        }
        public function mlink() 
        {
            $link = $this->params['link'];
            $dt= urlclick::makelink($link);
            header('Location: /index.php?controller=urlclick&action=go&code='.$dt);

        }
        public function listall() 
        {
            global $db,$user;
            $ajax = $this->params['ajax_action'];
            if(!$user->isLoggedIn())
            {                
                assign_to_template(array( 
                'error'=> 3
                ));
                return false;
            }  
            $cat = (int)$this->params['cat']; 
            $_last_day= time() - 24*60*60; 
            $sql='SELECT '.DB_TABLE_PREFIX.'_urlclick_list.id as id, '.DB_TABLE_PREFIX.'_urlclick_list.link as link,'.DB_TABLE_PREFIX.'_urlclick_list.name FROM `'.DB_TABLE_PREFIX.'_urlclick_list` 
            LEFT JOIN '.DB_TABLE_PREFIX.'_urlclick_user_logs
            ON exhscm_urlclick_list.id = '.DB_TABLE_PREFIX.'_urlclick_user_logs.link_id
            WHERE '.DB_TABLE_PREFIX.'_urlclick_list.cat='.$cat.' 
            AND ('.DB_TABLE_PREFIX.'_urlclick_user_logs.user_id is null OR '.DB_TABLE_PREFIX.'_urlclick_user_logs.user_id='.$user->id.' )
            AND ('.DB_TABLE_PREFIX.'_urlclick_user_logs.time is null OR '.DB_TABLE_PREFIX.'_urlclick_user_logs.time<'.$_last_day.')';
            $data=$db->selectObjectsBySql($sql);

            if($data!=null)
                foreach($data as $ii)
                {
                    $ii->link= '/index.php?controller=urlclick&action=go&code='.urlclick::makelink($ii->id);

            }
            expSession::set('s_url',null);  
            assign_to_template(array(
            'data'=>$data,
            'ajax'=>$ajax,
            ));
            // header('Location: /index.php?controller=urlclick&action=go&code='.$dt);

        }

        public function check()
        {
            global $db,$user;
            $res = (int)$this->params['result']; 
            $code = $this->params['code'];
            $key= md5((int)expSession::get("stime"));
            $data_de= json_decode(expCore::sdecode($code,$key)); 
            $data_link=$db->selectObject('urlclick_list',"id={$data_de->id}");
            
            if(expSession::get('s_url')!=null&&expSession::get('s_url')!=$data_de->id)
            {
                echo 'Có lỗi xảy ra 10923!' ; 
                return false;
            }      
            if($res==$_SESSION['capt_hash']) 
            {
                //Check time()
                $total_timeout=$data_link->timeout==0?10:$data_link->timeout;
                    //10 second
                    if((time()-$_SESSION['capt_time'])<$total_timeout)
                    {
                        echo 'Chưa đủ thời gian, vui lòng refresh và nhập lại!';
                        return false;
                    }
                $data_link->count=$data_link->count++;
                $db->updateObject($data_link,'urlclick_list');
                expSession::set('s_url',null);
                //Ghi vào logs
                $log=null;
                $log->link_id =$data_de->id;
                $log->user_id=$user->id;
                $log->time=time();
                $db->insertObject($log,'urlclick_user_logs');
                echo 'ok'  ;

            }
            else
                echo 'Sai rồi!' ; 
        }
        
        function testtime()
        {
            $total=time()-mktime(0,0,0,5,31,1992);
           echo $total;
            echo '<br>'.$total/60/60/24;
            echo '<br>'.date("d/m/Y H:i:s",mktime(0,0,0,3,27,1991));
        }

    }

?>